<?php
/**
* 采用RC4为核心算法，通过加密或者解密用户信息
* @param $string - 加密或解密的串
* @param $operation - DECODE 解密；ENCODE 加密
* @param $key - 密钥 默认为qsfPHP_AUTHKEY常量
* @return 返回字符串
*/
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	/**
	* $ckey_length 随机密钥长度 取值 0-32;
	* 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
	* 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
	* 当此值为 0 时，则不产生随机密钥
	*/
	$ckey_length = 4;
	$key = md5($key ? $key : AppConfig::$authKkey);
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}

}

/**
* 将特殊字符转成 HTML 格式。比如<a href='test'>Test</a>转换为&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
* @param string $value - 字符串或者数组变量
* @return array
*/
function _htmlspecialchars($value) {
	return is_array($value) ? array_map('_htmlspecialchars', $value) : preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1', str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $value));
}

/**
* 设置cookie
* @param $var - 变量名
* @param $value - 变量值
* @param $life - 生命周期期
* @param $prefix - 前缀
*/
function _setCookie($var, $value, $life = 0, $prefix = 1) {
	global $_SGLOBAL;
	setcookie(($prefix ? AppConfig::$cookie['cookiepre'] : '').$var, $value, $life ? $_SGLOBAL['timestamp'] + $life : 0, AppConfig::$cookie['cookiepath'], AppConfig::$cookie['cookiedomain'], $_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
}


/**
 +----------------------------------------------------------
 * 字节格式化 把字节数格式为 B K M G T 描述的大小
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function byte_format($size, $dec=2) {
    $a = array("B", "KB", "MB", "GB", "TB", "PB");
    $pos = 0;
    while ($size >= 1024) {
         $size /= 1024;
           $pos++;
    }
    return round($size,$dec)." ".$a[$pos];
}

/**
* 获取cookie
* @param $var - 变量名
*/
function _getCookie($var, $prefix = 1) {
	return $_COOKIE[($prefix ? AppConfig::$cookie['cookiepre'] : '').$var];
}


//产生form防伪码
function formhash() {
	global $_SGLOBAL;
	if(empty($_SGLOBAL['formhash'])) {
		$hashadd = defined('IN_ADMINCP') ? 'Only For UCenter Home AdminCP' : '';
		$_SGLOBAL['formhash'] = substr(md5(substr($_SGLOBAL['timestamp'], 0, -7).'|'.$_SGLOBAL['uid'].'|'.md5(AppConfig::$sitekey).'|'.$hashadd), 8, 8);
	}
	return $_SGLOBAL['formhash'];
}


//判断提交是否正确
function submitcheck($var) {
	if(!empty($_POST[$var]) && $_SERVER['REQUEST_METHOD'] == 'POST') {
		if((empty($_SERVER['HTTP_REFERER']) || preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) == preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])) && $_POST['formhash'] == formhash()) {
			return true;
		} else {
			showmessage('submit_invalid');
		}
	} else {
		return false;
	}
}

/**
* 终止程序执行，显示提示信息
* @param string $message 显示的信息文本
* @param string $urlForward 跳转地址，默认为空
* @param string $time 链接跳转时间，默认为3秒
* @return 无返回值
*/
function showmessage($message, $urlForward = '', $time = 3) {

	$message = $message;
	$title = $message;
	$urlForward = $urlForward;
	$time = $time * 1000;

	if($urlForward) {
		$message .= "<br><br><a href=\"$urlForward\">Check Here!</a>";
	}

	if($time) {
		$message .= "<script>".
			"function redirect() {window.location.replace('$urlForward');}\n".
			"setTimeout('redirect();', $time);\n".
			"</script>";
	}

	echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'.
		'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh" lang="zh">'.
		'<head profile="http://www.w3.org/2000/08/w3c-synd/#">'.
		'<meta http-equiv="content-language" content="zh-cn" />'.
		'<meta http-equiv="content-type" content="text/html;charset=gb2312" />'.
		'<title>'.$title.'</title>'.
		'<style type="text/css">'.
		'body { text-align:center; }'.
		'.notice{ padding: .5em .8em; margin:150px auto; border: 1px solid #ddd; font-family:verdana,Helvetica,sans-serif; font-weight:bold }'.
		'.notice{ width:500px; background: gray; color: #264409; border-color: #C6D880; }'.
		'.notice a{ color: #8a1f11; text-decoration: underline}'.
		'.notice a:hover{text-decoration: none}'.
		'.notice p{text-align:center;}'.
		'</style>'.
		'</head>'.
		'<body>'.
		'<div class="notice">'.
		'	<p>'.$message.'</p>'.
		'</div>'.
		'</body>'.
		'</html>';

	exit;
}



/**
* 获取当前用户信息
* @return 返回全局变量$MooUid, $MooUserName
*/
function getUserInfo() {

}



/**
* 获取文件内容
* @param string $filename 文件完整路径
* @return string $content 文件内容
*/
function _readfile($filename) {
	$content = '';
	if(function_exists('file_get_contents')) {
		@$content = file_get_contents($filename);
	} else {
		if(@$fp = fopen($filename, 'r')) {
			@$content = fread($fp, filesize($filename));
			@fclose($fp);
		}
	}
	return $content;
}


/**
* 写入文件
* @param string $filename  文件完整路径
* @param string $writetext 文件内容
* @param string $openmod   打开文件方式
* @return bool 写入成功为true 失败为false
*/
function _writefile($filename, $writetext, $openmod='w') {
	if(@$fp = fopen($filename, $openmod)) {
		flock($fp, 2);
		fwrite($fp, $writetext);
		fclose($fp);
		return true;
	} else {
		exit("error ：File $filename write error");
		return false;
	}
}



//格式化大小函数
function formatsize($size) {
	$prec=3;
	$size = round(abs($size));
	$units = array(0=>" B ", 1=>" KB", 2=>" MB", 3=>" GB", 4=>" TB");
	if ($size==0) return str_repeat(" ", $prec)."0$units[0]";
	$unit = min(4, floor(log($size)/log(2)/10));
	$size = $size * pow(2, -10*$unit);
	$digi = $prec - 1 - floor(log($size)/log(10));
	$size = round($size * pow(10, $digi)) * pow(10, -$digi);
	return $size.$units[$unit];
}


//用户验证
function checkauth() {
	return true;
}